package com.mdyy.servlet;

import com.mdyy.entity.FileInfo;
import com.mdyy.util.HDFSUtil;
import org.apache.hadoop.fs.FileStatus;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/fileDeleteServlet")
public class FileDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        String fileName = request.getParameter("fileName");

        HDFSUtil.deleteFile(fileName);
        doPost(request, response);

    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        FileStatus[] files = HDFSUtil.listFile();
        List<FileInfo> listFile = new ArrayList<FileInfo>();
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

        for(FileStatus fs : files) {
            long modificationTime = fs.getModificationTime();
            String modifyTime = dateFormat.format(modificationTime);
            Double len = fs.getLen()/1048576D;
            String format = String.format("%.2f", len);
            FileInfo file = new FileInfo(fs.getPath().getName(), format+"MB", modifyTime);
            listFile.add(file);
        }

        request.setAttribute("fileInfos", listFile);
        request.getRequestDispatcher("main.jsp").forward(request, response);
    }
}
